package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.user.RegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Component
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    JavaMailSender javaMailSender;
    //注册账号,插入用户表
    @Override
    public int insertUser(UserRegisterRequest userRequest) {
        //先对邮箱做一个查询
        String email = userRequest.getEmail();
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email",email);
        List<Member> members = memberMapper.selectByExample(example);
        //数据库内如果有这个邮箱则返回404
        if (members.size() != 0){
            return 404;
        }
        //判断用户名是否重复
        List<Member> mea = queryUsername(userRequest);
        if (mea.size() != 0){
            return 405;
        }
        //不重复则往下走，先插入用户表的信息
        String userName = userRequest.getUserName();
        //给密码加密
        String userPwd = userRequest.getUserPwd();
        AESUtil aesUtil = new AESUtil(userPwd);
        String encrypt = aesUtil.encrypt();
        Member member = new Member();
        //封装,先插入用户表的信息
        member.setUsername(userName);
        member.setPassword(encrypt);
        member.setEmail(email);
        member.setCreated(new Date());
        member.setUpdated(new Date());
        int i = memberMapper.insertSelective(member);
        return i;
    }

    /**  判断用户名是否重复
     *   */
    private List<Member> queryUsername(UserRegisterRequest userRequest) {
        String userName = userRequest.getUserName();
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",userName);
        List<Member> members = memberMapper.selectByExample(example);
        return members;
    }


    //注册账号,插入UserVerify表
    @Override
    public UserRegisterResponse insertUserVerify(UserRegisterRequest userRequest, String uuid) {
        //插入注册表
        String userName = userRequest.getUserName();
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(userName);
        userVerify.setRegisterDate(new Date());
        userVerify.setUuid(uuid);
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        int i = userVerifyMapper.insert(userVerify);
        //插入失败
        UserRegisterResponse response = new UserRegisterResponse();
        if (i != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED .getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED .getMessage());
            return response;
        }
        //发送邮件
        new Thread(() -> sendEmail(uuid,userRequest)).start();
        //打印日志
        log.info("注册成功，注册参数request：{}", JSON.toJSONString(userRequest));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    //发邮件方法
    private void sendEmail(String uuid, UserRegisterRequest userRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("jinlei7665@163.com");
        message.setTo(userRequest.getEmail());
        message.setSubject("用户激活");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("http://localhost:8080/user/verify?uuid=")
                .append(uuid)
                .append("&username=")
                .append(userRequest.getUserName());
        message.setText(stringBuffer.toString());
        javaMailSender.send(message);
    }

}
